<?php
namespace common\tools;

use Yii;
use yii\log\Logger;

/**
 * Description of WeiChatTool
 *
 * @author weiwang
 * 微信相关工具
 */
class WeChatTool {
    private static $_ticketName = "jsapi_ticket";
    private static $_tokenName  = "access_token";
    
    /**
     * 获取签名的随机串
     * @param int $length 随机串长度
     * @return string $str 随机串
     */
    public static function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
          $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    
    /**
     * 处理票据
     * @param bool $share 是否为分享票据（1是分享，2非分享）
     * @return string $str 票据串
     */
    public static function getJsApiTicket() {
        $weixinPath = Yii::getAlias("@common/cache").'/'.Yii::$app->params["weixinConf"]["weixinPath"];
        $fileName   = $weixinPath.'/'.self::$_ticketName.'.json';     
        $data = json_decode(file_get_contents($fileName));
        if ($data->expire_time < time()) {
            $accessToken = self::getToken();
            $url ="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$accessToken&type=jsapi";
            $res = json_decode(HttpTool::http_get($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $fp = fopen($fileName, "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }
        return $ticket;
    }
    /**
     * 获取签名
     */
    public static function getSignature($time,$nonceStr) {
        $jsapiTicket = self::getJsApiTicket();
   
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp={$time}&url=$url";
        return sha1($string);      
    }
    /**
     * 获取token
     * @return string $token_str 票据串
     */
    public static function getToken() {
        $weixinConf = Yii::$app->params["weixinConf"];
        $weixinPath = Yii::getAlias("@common/cache").'/'.$weixinConf["weixinPath"];     
        $fileName   = $weixinPath.'/'.self::$_tokenName.'.json';     
	$data = json_decode(file_get_contents($fileName));
	if ($data->expire_time < time()) {
            $appid        = $weixinConf['appid'];          
            $appsecret    = $weixinConf['appsecret'];              	      
            $url          = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";		  
            $res          = json_decode(HttpTool::http_get($url));
            $access_token = $res->access_token;
            if ($access_token) {
		$data->expire_time  = time() + 7000;
		$data->access_token = $access_token;
		$fp = fopen($fileName, "w");
		fwrite($fp, json_encode($data));
		fclose($fp);
            }
	} else {
            $access_token = $data->access_token;
	}
	return $access_token;               
    }
     /**
     * 跳授权页
     * @param $callBackUrl 回调页面 
     * 跳微信app授权成功回调
     */
    public static function goWeiChatOauth2($callBackUrl) {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($user_agent, 'MicroMessenger')) {
            // 微信浏览器appid
            $weixinConf = Yii::$app->params["weixinConf"];
            $location = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$weixinConf['appid']}&redirect_uri={$callBackUrl}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
            
            echo "<script language='javascript'>window.location='$location '</script>";die;
           // header("location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxcc3c0f27186417af&redirect_uri=http://ju3ban.com/login/oauth2&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect");die;
        }     
    }
     /**
     * 跳关注
     * @param $callBackUrl 回调页面 
     */
    public static function goWeiChatGuanZhu($guanZhuUrl) {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($user_agent, 'MicroMessenger')) {           
            echo "<script language='javascript'>window.location='$guanZhuUrl '</script>";die;        
        }     
    }
    /**
     * 获取微信用户信息
     * @param type $openid
     * @return string $infojson
     */
    public static function getUserInfo($openid){
        $token = self::getToken();
        $url   = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$openid}&lang=zh_CN";
        return json_decode(HttpTool::http_get($url));
    } 
    /**
     * 下载微信图片
     * @param type $mediaId
     * @return string imageurl
     */
    public static function getImageMedia($mediaId){
        $token = self::getToken();
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$token}&media_id={$mediaId}";
        return $url;
    }
}
